package main

import (
	"fmt"
	"github.com/gin-gonic/gin"
	"net/http"
	"time"
)

//统计耗时请求耗时
func computeCost() gin.HandlerFunc {
	return func(context *gin.Context) {
		start := time.Now()
		context.Set("message", "Hello")
		context.Next()
		cost := time.Since(start)
		fmt.Printf("处理耗时%d：", cost)
	}
}

func main() {
	engine := gin.Default()
	//全局注册中间件
	engine.Use(computeCost())
	//下面的第二个参数就是一个中间件，可以传入多个
	engine.GET("/demo", func(context *gin.Context) {
		//从上下文取值
		value, exists := context.Get("message")
		if exists {
			context.JSON(http.StatusOK, gin.H{"msg": value})
		}
	})
	engine.Run(":8088")
}
